# Definition for a binary tree node.
from typing import Optional, List


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:
        to_delete_set = set(to_delete)
        res = []

        def dfs(node: Optional[TreeNode]):
            nonlocal to_delete_set, res

            if node is None:
                return
            if node.left:
                dfs(node.left)
                if node.left.val in to_delete_set:
                    node.left = None
            if node.right:
                dfs(node.right)
                if node.right.val in to_delete_set:
                    node.right = None
            if node.val in to_delete_set:
                if node.left:
                    res.append(node.left)
                if node.right:
                    res.append(node.right)

        dfs(root)
        if root.val not in to_delete_set:
            res.append(root)
        return res
